<template>
  <div>
    <!-- 产品搜索 -->
    <div class="list-header">
      <Breadcrumb></Breadcrumb>
      <div class="form">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="产品名称">
            <el-input v-model="formInline.name" placeholder="产品名称" size="small" @blur="blur"></el-input>
          </el-form-item>
          <el-form-item label="选择日期">
            <el-date-picker v-model="formInline.date" type="date" placeholder="选择日期" size="small">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit" size="small">查询</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="list-group">
        <el-button size="small" type="success" icon='el-icon-plus' @click="toProductPage">添加商品</el-button>
        <el-button size="small" type="danger" icon="el-icon-delete" el-icon-delete-solid @click="delectAll">批量删除商品</el-button>
      </div>

    </div>

    <!-- 产品列表 -->
    <div class="list-content">
      <el-table :data="tableData" style="width: 100%" border header-row-class-name="activeHeader" @select="handleSelect" @select-all="handleSelect">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="商品编号" width="100">
        </el-table-column>
        <el-table-column prop="title" label="商品名称" width="100">
          <template slot-scope="scope">
            <span style="color:blue" @click="handleLook(scope.$index,scope.row)">
            {{ scope.row.title }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="商品价格" width="80">
        </el-table-column>
        <el-table-column prop="category" label="商品类目">
        </el-table-column>
        <el-table-column prop="create_time" label="商品时间">
          <template slot-scope="scope">
            <span>
              <!-- {{ scope.row.create_time }} -->
              {{ moment(scope.row.create_time).format('YYYY-MM-DD HH:mm:ss') }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="sellPoint" label="商品卖点">
        </el-table-column>
        <el-table-column label="商品描述">
          <template slot-scope="scope">
            <span>
              {{ removeHTMLTag(scope.row.descs) }}
            </span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="address" label="地址">
        </el-table-column> -->

        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button size="mini" 
            @click="handleEdit(scope.$index, scope.row)" 
            icon="el-icon-edit-outline">编辑</el-button>
            <el-button size="mini" type="danger" 
            @click="handleDelete(scope.$index, scope.row)" 
            icon="el-icon-delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="Pagination">
        <Pagination :total="total" :page-size="pageSize" @CurrentChange="CurrentChange"></Pagination>
      </div>
    </div>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination/Pagination.vue'
import moment from 'moment'
import { removeHTMLTag } from '@/utils/common'//引入方法
import { mapMutations } from 'vuex'

export default ({
  components: { Pagination },
  data() {
    return {
      formInline: {
        name: '',
        date: ''
      },
      tableData: [],
      total: 10,
      pageSize: 1,
      current: 1,
      ids: [],//存储选中的id
    }
  },
  methods: {
    moment,//注册方法
    removeHTMLTag,
    ...mapMutations('product',['changeRowData','changeTitle']),
    onSubmit() {
      console.log('submit!', this.formInline.name);
      this.search(this.formInline.name)
    },
    //查看商品操作
    handleLook(index, row){
      this.changeRowData(row)
      this.changeTitle('详情')//调用vuex 改变title
      //跳转编辑界面
      this.$router.push('/product/ProductPage');
    },
    //编辑
    handleEdit(index, row) {
      console.log(index, row);//row为编辑当前行的数据
      //存储当前行的数据 --vuex ，再跳转
      this.changeRowData(row)
      this.changeTitle('编辑')//调用vuex 改变title
      //跳转编辑界面
      this.$router.push('/product/ProductPage');
    },
    handleSelect(selection) {//表单勾选
      console.log('表单勾选', selection);
      let arr = [];
      selection.forEach(ele => {
        arr.push(ele.id)
        this.ids = arr
      });
    },

    delectAll() {//批量勾选删除
      let idStr = this.ids.join(',');
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let res = this.$api.batchDelete({ ids: idStr })
          .then(res => {
            console.log('批量勾选删除', res.data);

            if (res.data.status === 200) {

              //删除成功提示
              this.$message({
                type: 'success',
                message: '删除成功!'
              });

              //获取当前页是否时最后一页
              //当前数据展示多少页码  18/8=3 
              let maxPage = Math.ceil(this.total/this.pageSize);
              //获取选中个数
              let len = this.ids.length;
              //分析：如果点最后一页，删除个数等于最后一页的余数，则页码高亮-1，请求-1的页码
              //更新视图
              if(this.current==maxPage){   //如果点击的页码等于最后一页
  // 最后一页有多少条数据： 余数为0 ，最后一页有8条数据       8条          余数，最后一页有余数条
                let num = this.total%this.pageSize==0?this.pageSize:this.total%this.pageSize
                if(num===len){//最后一页的条数=勾选的条数，则该页为空，要去上一条页码
                  this.current=this.current-1>0?this.current-1:1
                }
              }
              this.projectList(this.current)
            };
          })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    toProductPage() {//点击添加商品
      console.log('add product');
      this.$router.push('/product/ProductPage')
      this.changeTitle('添加')//调用vuex 改变title

    },

    //删除商品
    handleDelete(index, row) {
      console.log(index, row);
      this.$confirm('此操作将永久删除该条商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteItemById(row.id)

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //获取产品列表数据
    async projectList(page) {
      let res = await this.$api.projectList({ page })
      console.log('产品列表数据----', res.data);
      this.tableData = res.data.data
      this.total = res.data.total
      this.pageSize = res.data.pageSize
    },
    //搜索接口
    async search(search) {
      let res = await this.$api.search({ search });
      console.log('搜索结果', res.data);
      if (res.data.status === 200) {
        this.tableData = res.data.result;
        this.total = res.data.result.length;
        this.pageSize = res.data.result.length;
      } else {
        this.tableData = [];
        this.total = 1;
        this.pageSize = 1
      }
    },
    //删除产品
    async deleteItemById(id) {
      let res = await this.$api.deleteItemById({ id });
      console.log('删除产品', res.data);
      if (res.data.status === 200) {
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        //删除时当前页码只有一条
        if (this.total % this.pageSize === 1) {
          this.current = this.current - 1 > 0 ? this.current - 1 : 1;//最好>1 
        }
        //重新渲染
        this.projectList(this.current)
      };

    },
    blur() {
      if (!this.formInline.name) {
        this.projectList(1)
      }
    },
    CurrentChange(val) {//当前页码
      // console.log('我是父组件，拿到子组件值为', val)
      this.current = val
      this.projectList(val)

    }
  },
  created() {
    this.projectList();
  }
})
</script>

<style lang="less" scoped>
.list-header {
  background-color: #fff;
  margin-bottom: 20px;
  padding: 10px;
  .el-form-item {
    margin-bottom: 15px;
  }
  .list-group {
  border: 1px solid #fff;
  padding: 7px;
}
}
.list-content {
  background-color: #fff;
  /deep/ .activeHeader {
    color: black;
    text-align: center;
  }
  .Pagination {
    padding: 10px;
  }
}
</style>